package com.beijiteshop.shop.ui.order.fragment

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import com.beijiteshop.libcommon.ext.databinding.inflateBinding
import com.beijiteshop.libcommon.utils.EventUtil
import com.beijiteshop.shop.R
import com.beijiteshop.shop.databinding.DialogOrderRefundBinding
import com.beijiteshop.shop.model.api.response.OrderDetailBean
import com.beijiteshop.shop.model.event.EventKey
import com.beijiteshop.shop.ui.order.vm.OrderVM
import com.blankj.utilcode.util.ToastUtils
import org.koin.android.viewmodel.ext.android.viewModel
import java.lang.NumberFormatException

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/18 14:54
 * @Description 填写退款原因弹框
 */
class OrderRefundDialog : DialogFragment() {

    private lateinit var mBinding: DialogOrderRefundBinding
    private var mRefundAmount: String = ""
    private var mRefundReason: String = ""
    private val mOrderVM: OrderVM by viewModel()
    private var mOrderDetailBean: OrderDetailBean? = null

    override fun onStart() {
        super.onStart()
        val dialog = dialog
        if (dialog != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                val windowManager = requireActivity().getSystemService(Context.WINDOW_SERVICE) as WindowManager
                val metrics = windowManager.currentWindowMetrics
                dialog.window?.setLayout( (metrics.bounds.width() * 0.9).toInt(), ViewGroup.LayoutParams.WRAP_CONTENT)
            }else{
                val metrics = DisplayMetrics()
                requireActivity().display?.getRealMetrics(metrics)
                dialog.window?.setLayout( (metrics.widthPixels * 0.9).toInt(), ViewGroup.LayoutParams.WRAP_CONTENT)
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = inflateBinding<DialogOrderRefundBinding>(inflater)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initEvent()
        setRefundDefaultValue()
    }

    fun showDialog(fm: FragmentManager,orderDetailBean: OrderDetailBean){
        mOrderDetailBean = orderDetailBean
        show(fm,"")
    }

    private fun initEvent(){

        startObserve()

        mBinding.orderRefundCloseBtn.setOnClickListener {
            dismiss()
        }
        mBinding.orderRefundCloseIv.setOnClickListener {
            dismiss()
        }
        //保存按钮
        mBinding.orderRefundPreserveBtn.setOnClickListener {
            if (checkInfo()){
                if (mRefundAmount.isNotEmpty() && mRefundReason.isNotEmpty()){
                    try {
                        val money = mRefundAmount.toFloat()
                        requestRefund(mOrderDetailBean!!.orderNumber,mRefundReason,money)
                    }catch (e: NumberFormatException){
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    private fun setRefundDefaultValue(){
        if (mOrderDetailBean != null){
            mBinding.orderRefundAmountEt.setText(mOrderDetailBean!!.sellingPrice)
        }
    }

    private fun checkInfo(): Boolean{
        if (mOrderDetailBean == null){
            return false
        }
        mRefundAmount = mBinding.orderRefundAmountEt.text.toString()
        mRefundReason = mBinding.orderRefundReasonEt.text.toString()
        if (mRefundAmount.isEmpty()){
            Toast.makeText(requireContext(),resources.getString(R.string.please_input_refund_amount),Toast.LENGTH_SHORT).show()
            return false
        }

        if (mRefundReason.isEmpty()){
            Toast.makeText(requireContext(),resources.getString(R.string.please_input_refund_reason),Toast.LENGTH_SHORT).show()
            return false
        }
        try {
            val money = mRefundAmount.toFloat()
            if (money > mOrderDetailBean!!.sellingPrice.toFloat()){
                Toast.makeText(requireContext(),resources.getString(R.string.refund_amount_limit),Toast.LENGTH_SHORT).show()
                return false
            }
        }catch (e: NumberFormatException){
            return false
        }
        return true
    }

    private fun requestRefund(orderNumber: String,reason: String,money: Float){
        mOrderVM.requestRefund(orderNumber, reason, money)
    }

    private fun startObserve(){
        mOrderVM.liveRefund.observe(this, Observer<Pair<Boolean, String?>> {
                val(success,message) = it
                if (success){
                    EventUtil.post(EventKey.REFUND_COMMIT)
                    dismiss()
                }else{
                    message?.let {msg ->
                        Toast.makeText(requireContext(),msg,Toast.LENGTH_SHORT).show()
                    }?:Toast.makeText(requireContext(),resources.getString(R.string.something_error),Toast.LENGTH_SHORT).show()
                }
            })
    }
}